package com.glwan.fixedassetapp.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.ui.login.LoginActivity;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class CommonUtil {

    public static final int SUCCESS = 0;
    public static final int WARNING_YELLOW = 1;
    public static final int ERROR = 2;
    public static final int WARNING_RED = 3;

    private static AlertDialog processDialog;

    private static long exitTime = 0;

    /**
     * 打开加载框
     */
    public static void openProgressDialog(Activity activity, String message) {
        activity.runOnUiThread(() -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            LayoutInflater inflater = LayoutInflater.from(activity);
            View dialogView = inflater.inflate(R.layout.dialog_loading, null);
            TextView progressMessage = dialogView.findViewById(R.id.progressMessage);
            progressMessage.setText(message);
            builder.setView(dialogView);
            builder.setCancelable(false); // 防止用户取消对话框
            processDialog = builder.create();
            processDialog.show();
        });
    }

    /**
     * 取消加载框
     */
    public static void cancelProgressDialog(Activity activity) {
        activity.runOnUiThread(() -> {
            processDialog.dismiss();
        });
    }

    /**
     * 打开通知框
     *
     * @param activity activity
     * @param message  message
     */
    public static void openAlertDialog(Activity activity, String title, String message, int icon) {

        activity.runOnUiThread(() -> {
            new android.app.AlertDialog.Builder(activity)
                    .setIcon(icon)
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton(activity.getString(R.string.confirm), null)
                    .show();
        });

    }


//    /**
//     * 打开确认通知框
//     */
//    public static void IntentConfirmDialog(Context context,Class<?> cls,String message,String positiveText,String negativeText){
//        new AlertDialog.Builder(context).setTitle(message)
//                .setPositiveButton(positiveText, (dialog, which) -> {
//                    // 点击“确认”后的操作
//                    startActivity(context,cls,true);
//                })
//                .setNegativeButton(negativeText, (dialog, which) -> {
//                    // 点击“取消”后的操作,这里不设置没有任何操作
//                }).show();
//    }

    /**
     * 退出程序
     *
     * @param context view对象
     * @return boolean
     */
    public static boolean exitApp(Context context) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(context.getApplicationContext(), R.string.PressAgainExitApp, Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
            return false;
        } else {
            //启动一个意图,回到桌面
            startActivity(context, null, null, true);
            return true;
        }
    }

    /**
     * 退出登录
     *
     * @param activity
     */
    public static void logout(Activity activity) {
        openProgressDialog(activity, activity.getString(R.string.loading));
        intentConfirmDialog(
                activity.getApplicationContext(),
                LoginActivity.class,
                R.drawable.warning_red,
                activity.getString(R.string.logoutConfirm),
                activity.getString(R.string.confirm),
                activity.getString(R.string.cancel),
                null,
                true);
        cancelProgressDialog(activity);
    }

    /**
     * 跳转页面
     * @param currentContext 当前的context
     * @param destination 目的class
     * @param category 是否为根页面
     */
//    public static void startActivity(Context currentContext,Class<?> destination,boolean category){
//        Intent intent = new Intent();
//        if(category){
//            intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
//            intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
//        }
//        if(destination != null)
//            intent.setClass(currentContext,destination);
//        currentContext.startActivity(intent); //将Intent传递给Activity
//    }

    /**
     * 跳转页面
     *
     * @param currentContext 当前的context
     * @param destination    目的class
     * @param map            传值map
     * @param category       是否为根页面
     */
    public static void startActivity(Context currentContext, Class<?> destination, Map<String, Object> map, boolean category) {
        Intent intent = new Intent();
        if (category) {
            intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
            intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (destination != null)
            intent.setClass(currentContext, destination);
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, Object> item : map.entrySet()) {
                intent.putExtra(item.getKey(), String.valueOf(item.getValue()));
            }
        }
        currentContext.startActivity(intent); //将Intent传递给Activity
    }

    /**
     * 设置打开文件管理器的参数
     *
     * @return Intent
     */
    private static Intent setActivityFileIntentParams() {
        Uri uri = Uri.parse(Environment.getExternalStorageState() + "/1EAM");
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "*/*");
        return intent;
    }

    /**
     * Activity中打开文件管理器
     *
     * @param activity activity
     */
    public static void startActivityFileManager(AppCompatActivity activity) {
        activity.startActivityForResult(setActivityFileIntentParams(), 0);
    }


    /**
     * Fragment中打开文件管理器
     *
     * @param fragment fragment
     */
    public static void startFragmentFileManager(Fragment fragment) {
        fragment.startActivityForResult(setActivityFileIntentParams(), 1);
    }

    /**
     * 获取activity
     *
     * @return
     */
    public static Activity getActivity() {
        Class activityThreadClass = null;
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    return activity;
                }
            }
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * toast show
     *
     * @param activity
     * @param message
     * @param isShort
     */
    public static void toastShow(Activity activity, String message, int type, boolean isShort) {
        activity.runOnUiThread(() -> {
            Toast toast = new Toast(activity);
            View inflate = LayoutInflater.from(activity).inflate(R.layout.layout_toast, null);
            ImageView imageView = inflate.findViewById(R.id.toast_iv);

            if (type == SUCCESS)
                imageView.setImageResource(R.drawable.success);
            else if (type == WARNING_YELLOW)
                imageView.setImageResource(R.drawable.warning_yellow);
            else if (type == ERROR)
                imageView.setImageResource(R.drawable.error);
            else if (type == WARNING_RED)
                imageView.setImageResource(R.drawable.warning_red);

            // ObjectAnimator.ofFloat(imageView, "rotationY", 0, 360).setDuration(2000).start();

            //创建TextView
            TextView textView = inflate.findViewById(R.id.toast_tv);
            textView.setText(message);
            textView.setTextSize(16);
            toast.setView(inflate);
            if (isShort) {
                toast.setDuration(Toast.LENGTH_SHORT);
            } else {
                toast.setDuration(Toast.LENGTH_LONG);
            }
            toast.show();
        });
    }

    /**
     * 打开跳转确认通知框
     */
    public static void intentConfirmDialog(Context context, Class<?> cls, int icon, String message, String positiveText, String negativeText, Map<String, Object> map, boolean category) {
        new AlertDialog.Builder(context).setTitle(context.getString(R.string.tips)).setMessage(message).setIcon(icon)
                .setPositiveButton(positiveText, (dialog, which) -> {
                    startActivity(context, cls, map, category);
                })
                .setNegativeButton(negativeText, (dialog, which) -> {
                    // 点击“取消”后的操作,这里不设置没有任何操作
                }).show();
    }

    public static String hexToString(String hex) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String str = hex.substring(i, i + 2);
            result.append((char) Integer.parseInt(str, 16));
        }
        return result.toString();
    }
}
